import path from "path";
import json from "@rollup/plugin-json";
import nodeResolve from "@rollup/plugin-node-resolve"; // 帮助寻找 node_modules 里的包
import ts from "rollup-plugin-typescript2";
import commonjs from "@rollup/plugin-commonjs"; // 将非 ES6 语法的包转为 ES6 可用
import { terser } from "rollup-plugin-terser";

// process.env.TARGET 是 rollup 命令执行时用户设置的参数，这里在 dev.js 或 build.js 中的调用 execa 设置的
// process.env.SOURCE_MAP 是 rollup 命令执行时用户设置的参数，这里在 dev.js 或 build.js 中的调用 execa 设置的
// process.env.FORMATS 是 rollup 命令执行时用户设置的参数，这里在 dev.js 或 build.js 中的调用 execa 设置的

const target = process.env.TARGET;
const sourcemap = process.env.SOURCE_MAP;
const packageFormats = process.env.FORMATS && process.env.FORMATS.split(",");

// console.log('target: ', target)
// console.log('sourcemap: ', sourcemap)
// console.log('packageFormats: ', packageFormats)

// 获取 packages
const packagesDir = path.resolve(__dirname, "packages");
// 获取需要打包的某个包
const packageDir = path.resolve(packagesDir, target);

const resolve = (_path) => path.resolve(packageDir, _path);

// 获取配置信息
const pkg = require(resolve("package.json"));
const name = path.basename(packageDir);

const outputConfig = {
  "esm-bundler": {
    file: resolve(`dist/${name}.esm-bundler.js`),
    format: "es",
  },
  cjs: {
    file: resolve(`dist/${name}.cjs.js`),
    format: "cjs",
  },
  global: {
    file: resolve(`dist/${name}.global.js`),
    format: "iife",
  },
};

// 自定义的打包的配置项
const options = pkg.buildOptions;
const packageConfigs = packageFormats || options.formats;

function createConfig(format, output) {
  // 是否生成 sourcemap
  output.sourcemap = sourcemap;
  output.exports = "named";
  let external = []; // 哪些模块不需要打包

  if (format === "global") {
    output.name = options.name;
  } else {
    external = [...Object.keys(pkg.dependencies)];
  }
  // 生成 rollup 配置信息
  return {
    input: resolve(`src/index.ts`),
    output,
    external,
    plugins: [
      json(),
      ts({
        tsconfig: path.resolve(__dirname, "tsconfig.json"),
      }),
      commonjs(),
      nodeResolve(),
    ],
  };
}

const banner = {
  plugins: [process.env.NODE_ENV === "development" ? null : terser()],
  banner: "/* min-vue3 version " + pkg.version + " */",
  footer: "/* follow me on Twitter! @Timly */",
};

export default packageConfigs.map((format) =>
  createConfig(format, Object.assign(outputConfig[format], banner))
);
